package com.kh.pajx.sop.view.action;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.base.SOPConfig;
import com.kh.pajx.sop.domain.HsEquipmentInfo;
import com.kh.pajx.sop.domain.SysArea;
import com.kh.pajx.sop.domain.SysInsideUser;
import com.kh.pajx.sop.domain.SysOutsideUser;
import com.kh.pajx.sop.domain.SysUserRole;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.common.FormatDate;
import com.kh.pajx.sop.util.common.ValidatorUtils;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.security.encoder.Md5PwdEncoderUtil;
import com.kh.pajx.sop.util.sop.PropertyValidate;
import com.opensymphony.xwork2.ActionContext;

/**
 * 外部用户对象Struts2控制器
 * 
 * @author: azzcsimp
 * @Createdate: 2014年7月21日 下午10:13:47
 */
@Controller
@Scope("prototype")
public class SysOutsideUserAction extends ModelDrivenBaseAction<SysOutsideUser> {

    private static final long serialVersionUID = -8226247427832674992L;
    private HttpServletRequest request;

    /** 列表 */
    public String list() {
	// ============参数校验================
	try {
	    if (!PropertyValidate.validateSafeString(model.getOsuName(), 12, true) && !PropertyValidate.validatePhone(model.getOsuName(), true)) {
		throw new Exception("检索条件[姓名或手机号]不符合规范！");
	    }

	    if (!PropertyValidate.validateNumberCode(model.getAreaCode(), 4, true)) {
		throw new Exception("检索条件[所属地区]不符合规范");
	    }

	    if (!PropertyValidate.validateNumberCode(model.getAreaChildcode(), 6, true)) {
		throw new Exception("检索条件[所属县区]不符合规范");
	    }

	    request = ServletActionContext.getRequest();
	    // 准备外部用户分页列表数据
	    new QueryHelper(SysOutsideUser.class, "osu").addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getOsuName())), "(osu.osuName like ? or osu.osuPhone=? )", "%" + StringUtils.trim(model.getOsuName()) + "%", StringUtils.trim(model.getOsuName())).addCondition(model.getOsuType() > -1, "osu.osuType=?", model.getOsuType()).addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getAreaCode())), "osu.areaCode=?", StringUtils.trim(model.getAreaCode())).addCondition(StringUtils.isNotEmpty(StringUtils.trim(model.getAreaChildcode())), "osu.areaChildcode=?", StringUtils.trim(model.getAreaChildcode())).addOrderProperty("osu.createTime", false).preparePageBean(sysOutsideUserService, pageNum, numPerPage);

	    // 准备用户角色信息
	    List<SysUserRole> userRoleList = sysUserRoleService.findAll();
	    ActionContext.getContext().put("userRoleList", userRoleList);
	    Map<String, List<SysArea>> map = (Map<String, List<SysArea>>) ActionContext.getContext().getApplication().get("areaChild");
	    List<SysArea> countyList = map.get(model.getAreaCode());
	    if (countyList != null) {
		request.setAttribute("countyList", countyList);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    ActionContext.getContext().put("errorMsg", "检索失败！" + e.getMessage());
	}
	return "list";
    }

    /** 添加页面 */
    public String addUI() {
	return "saveUI";
    }

    /** 添加 */
    public void add() {
	DwzAjaxResult dwz = new DwzAjaxResult();
	try {
	    validateProperty(model);
	    // 用户类型
	    if (model.getOsuType() == 1) { // 移动客户经理
		model.setOsuRoleCode(SOPConfig.CODE_USER_ROLE_CHINAMOBILE);
	    } else if (model.getOsuType() == 0) { // 学校管理员
		model.setOsuRoleCode(SOPConfig.CODE_USER_ROLE_SCHOOLMANAGER);
	    }
	    model.setOsuName(StringUtils.trim(model.getOsuName())); // 姓名
	    model.setAreaCode(StringUtils.trim(model.getAreaCode())); // 地区编码
	    model.setAreaChildcode(StringUtils.trim(model.getAreaChildcode()));// 区县编码
	    // 性别
	    model.setOsuPhone(StringUtils.trim(model.getOsuPhone())); // 手机
	    model.setOsuEmail(StringUtils.trim(model.getOsuEmail())); // 邮箱
	    model.setRemark(StringUtils.trim(model.getRemark())); // 备注
	    model.setAccount(model.getOsuPhone()); // 登录帐号
	    model.setPassword(Md5PwdEncoderUtil.encrytion("00000000")); // 登录密码
	    model.setOsuStatusFlag(1); // 状态
	    model.setCreateTime(FormatDate.dateTimeDetail()); // 创建时间
	    model.setCreateOperId(getCurrentUser().getUserId()); // 创建人
	    if (sysOutsideUserService.checkPhone(model.getOsuPhone(), model.getOsuId())) {
		sysOutsideUserService.save(model);
		dwz.setMessage("保存成功！");
		dwz.setCallbackType("closeCurrent");
		dwz.setNavTabId("outsideUser_list");
		dwz.setStatusCode("200");
		DwzAjaxResult.josnMessage(dwz);
	    } else {
		dwz.setMessage("保存失败！<br>手机号已存在！");
		dwz.setStatusCode("300");
		DwzAjaxResult.josnMessage(dwz);
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    dwz.setMessage("保存失败！<br>错误信息：" + e.getMessage());
	    dwz.setStatusCode("300");
	    DwzAjaxResult.josnMessage(dwz);
	}
    }

    /** 修改页面 */
    public String editUI() {
	request = ServletActionContext.getRequest();
	// 准备用户信息
	SysOutsideUser outsideUser = sysOutsideUserService.getById(StringUtils.trim(model.getOsuId()));
	ActionContext.getContext().getValueStack().push(outsideUser);
	Map<String, List<SysArea>> map = (Map<String, List<SysArea>>) ActionContext.getContext().getApplication().get("areaChild");
	List<SysArea> countyList = map.get(outsideUser.getAreaCode());
	if (countyList != null) {
	    request.setAttribute("countyList", countyList);
	}
	return "saveUI";
    }

    /** 修改 */
    public void edit() {
	DwzAjaxResult dwz = new DwzAjaxResult();
	try {
	    validatePropertysByUpdate(model);
	    SysOutsideUser outsideUser = sysOutsideUserService.getById(StringUtils.trim(model.getOsuId()));
	    outsideUser.setOsuType(model.getOsuType());
	    if (model.getOsuType() == 1) { // 移动客户经理
		outsideUser.setOsuRoleCode(SOPConfig.CODE_USER_ROLE_CHINAMOBILE);
	    } else if (model.getOsuType() == 0) { // 学校管理员
		outsideUser.setOsuRoleCode(SOPConfig.CODE_USER_ROLE_CHINAMOBILE);
	    }
	    outsideUser.setOsuName(StringUtils.trim(model.getOsuName())); // 姓名
	    outsideUser.setOsuSex(model.getOsuSex()); // 性别
	    outsideUser.setAreaCode(model.getAreaCode()); // 地区
	    outsideUser.setAreaChildcode(model.getAreaChildcode());// 县区
	    outsideUser.setOsuPhone(StringUtils.trim(model.getOsuPhone())); // 手机
	    outsideUser.setAccount(StringUtils.trim(model.getOsuPhone()));
	    outsideUser.setOsuEmail(StringUtils.trim(model.getOsuEmail())); // 邮箱
	    outsideUser.setRemark(StringUtils.trim(model.getRemark())); // 备注
	    if (sysOutsideUserService.checkPhone(model.getOsuPhone(), model.getOsuId())) {
		// System.out.println(out);
		sysOutsideUserService.update(outsideUser);
		dwz.setMessage("修改成功！");
		dwz.setCallbackType("closeCurrent");
		dwz.setNavTabId("outsideUser_list");
		dwz.setStatusCode("200");
		DwzAjaxResult.josnMessage(dwz);
	    } else {
		dwz.setMessage("修改失败！<br>手机号已存在！");
		dwz.setStatusCode("300");
		DwzAjaxResult.josnMessage(dwz);
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    dwz.setMessage("修改失败！<br>错误信息：" + e.getMessage());
	    dwz.setStatusCode("300");
	    DwzAjaxResult.josnMessage(dwz);
	}
    }

    /** 更改状态 */
    public void updateFlag() {
	DwzAjaxResult dwz = new DwzAjaxResult();
	try {
	    SysOutsideUser outsideUser = sysOutsideUserService.getById(model.getOsuId());
	    dwz.setMessage("已成功" + (outsideUser.getOsuStatusFlag() == 1 ? "停用" : "启用") + "用户<font color='red'>" + outsideUser.getOsuName() + "</font>!");
	    outsideUser.setOsuStatusFlag(outsideUser.getOsuStatusFlag() == 1 ? 0 : 1);
	    sysOutsideUserService.update(outsideUser);
	    dwz.setNavTabId("outsideUser_list");
	    dwz.setStatusCode("200");
	    DwzAjaxResult.josnMessage(dwz);
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /** 删除 */
    public void delete() {
	// TODO: 判断有无数据需要处理
	DwzAjaxResult dwz = new DwzAjaxResult();
	try {
	    sysOutsideUserService.delete(model.getOsuId());
	    dwz.setMessage("删除成功!");
	    dwz.setNavTabId("outsideUser_list");
	    dwz.setStatusCode("200");
	    DwzAjaxResult.josnMessage(dwz);
	} catch (Exception e) {
	    e.printStackTrace();
	    dwz.setMessage("删除失败!<br>错误信息：" + e.getMessage());
	    dwz.setStatusCode("300");
	    DwzAjaxResult.josnMessage(dwz);
	}
    }

    /** 查看 */
    public String show() {
	if (!PropertyValidate.validateUUID(model.getOsuId(), false)) {
	    return null;
	} else {
	    // 准备用户信息
	    SysOutsideUser outsideUser = sysOutsideUserService.getById(StringUtils.trim(model.getOsuId()));
	    ActionContext.getContext().getValueStack().push(outsideUser);
	    return "show";
	}

    }

    /** 密码重置 */
    public void resetPwd() {
	DwzAjaxResult dwz = new DwzAjaxResult();
	try {
	    SysOutsideUser outsideUser = sysOutsideUserService.getById(StringUtils.trim(model.getOsuId()));
	    outsideUser.setPassword(Md5PwdEncoderUtil.encrytion("00000000"));
	    sysOutsideUserService.update(outsideUser);
	    dwz.setMessage("密码重置成功!");
	    dwz.setNavTabId("outsideUser_list");
	    dwz.setStatusCode("200");
	    DwzAjaxResult.josnMessage(dwz);
	} catch (Exception e) {
	    e.printStackTrace();
	    dwz.setMessage("密码重置失败!<br>错误信息：" + e.getMessage());
	    dwz.setStatusCode("300");
	    DwzAjaxResult.josnMessage(dwz);
	}
    }

    public String getSimpleByAreaCode() {
	List outsideUserList = sysOutsideUserService.getSimpleUserByCountyCode(model.getAreaCode(), model.getOsuType(), 1);
	ActionContext.getContext().put("outsideUserList", outsideUserList);
	return "getSimpleByAreaCode";
    }

    public void checkPhone() {
	PrintWriter out = null;
	request = ServletActionContext.getRequest();
	try {
	    out = ServletActionContext.getResponse().getWriter();
	    String useId = request.getParameter("outUserId");
	    if (sysOutsideUserService.checkPhone(model.getOsuPhone(), useId)) {
		out.write("true");
	    } else {
		out.write("false");
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    if (out != null) {
		out.close();
	    }
	}
    }

    private void validateProperty(SysOutsideUser model) throws Exception {
	if (!ValidatorUtils.validateFixedLengthNumber(model.getAreaCode(), 4, false)) {
	    throw new Exception("地区信息不符合规范");
	}
	if(!ValidatorUtils.validateFixedLengthNumber(model.getAreaChildcode(), 6, true)){
	    throw new Exception("区县信息不符合规范");
	}
	if (!ValidatorUtils.validateFixedLengthNumber(model.getOsuType(), 1, false)) {
	    throw new Exception("用户组信息不符合规范");
	}
	if (!ValidatorUtils.validateSafeString(model.getOsuName(), 20, false)) {
	    throw new Exception("用户姓名不符合规范");
	}
	if (!ValidatorUtils.validateFixedLengthNumber(model.getOsuSex(), 1, true)) {
	    throw new Exception("用户性别不符合规范");
	}
	if (!ValidatorUtils.validatePhone(model.getOsuPhone(), false)) {
	    throw new Exception("用户手机号不符合规范");
	}
	if (!ValidatorUtils.validateEmail(model.getOsuEmail(), false)) {
	    throw new Exception("用户电子邮箱不符合规范");
	}
	if (!ValidatorUtils.validateRelativeSafeString(model.getRemark(), 200, true)) {
	    throw new Exception("用户描述不符合规范");
	}

    }
    
    private void validatePropertysByUpdate(SysOutsideUser model) throws Exception {
	if(!ValidatorUtils.validateUUID(model.getOsuId(), false)){
	    throw new Exception("用户编号输入不符合规范");
	}
	validateProperty(model);
    }
}
